<template>
  <div class="app-container app-container-main">
    <!-- 操作 -->
    <div class="crud">
      <div>
        <!-- <el-button class="fill-btn" @click="handleUpdate(-1, 'create')">添加</el-button> -->
        <el-button class="plain-btn" @click="handleDelmultip">删除</el-button>
      </div>
      <div class="search">
        <el-input v-model="listQuery.keyword" placeholder="查找关键字" class="crud-input">
          <el-button class="search-btn" slot="append" icon="el-icon-search" @keyup.enter.native="handleFilter"
            @click="handleFilter" />
        </el-input>
      </div>

    </div>

    <!-- 0 table表格 -->
    <el-table :key="tableKey" v-loading="listLoading" element-loading-text="数据加载中"
      element-loading-spinner="el-icon-loading" :data="list" border fit highlight-current-row style="width: 100%;"
      @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属公司" width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.groupName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" width="160" align="center">
        <template slot-scope="{row}">
          <span>{{ row.deviceName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始结束时间" min-width="190" align="center">
        <template slot-scope="{row}">
          <span>{{ row.resStartTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          ~
          <span>{{ row.resStopTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" prop="createTime" sortable min-width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" min-width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <!-- <el-button v-if="row.status !== 1" plain round :loading="true">加载中</el-button>
          <el-button v-if="row.status === 1" type="primary" plain round @click="download(row.downloadLink, row.startTime, row.endTime)">点击下载</el-button> -->
          <span class="action action-update" @click="handleDownload(row)">下载</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.offset" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <!-- 删除的提示框 -->
    <el-dialog :visible.sync="dialogPvVisible" title="提示" width="30%" center>
      <div class="del-data del-img"><img :src="require('../../assets/img/del.png')" alt=""></div>
      <div class="del-data del-notify">确定对账号进行【删除】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="plain-dialog-btn" @click="dialogPvVisible = false">取消</el-button>
        <el-button class="fill-dialog-btn" @click="delData">确认</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import waves from '@/directive/waves' // waves directive
  import {
    parseTime
  } from '@/utils' // 解析时间
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import {
    listDownload,
    sureDownload,
    sourceDownload,
    typeDownload,
    delDownload
  } from '@/api/video'

  import {
    validPass
  } from '@/utils/validate'
  import {
    logger
  } from 'runjs/lib/common'
  const calendarTypeOptions = [{
      key: 'CN',
      display_name: 'China'
    },
    {
      key: 'US',
      display_name: 'USA'
    },
    {
      key: 'JP',
      display_name: 'Japan'
    },
    {
      key: 'EU',
      display_name: 'Eurozone'
    }
  ]

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'BranchDevice',
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      const validatePassword = (rule, value, callback) => {
        // if (!validPass(value) && (value && value.length != 64)) {
        if (!validPass(value)) {
          callback(new Error('8~16位,包含大小写字母和数字, 可以有特殊字符'))
        } else {
          callback()
        }
      }

      return {
        multipleSelection: [],
        is_multip: false, // 是否批量删除
        tableKey: 0,
        // list: null,
        list: [],
        total: 0, // 总条数
        listLoading: false,
        listQuery: {
          offset: 1, // 第几页
          limit: 10, // 每页显示的条数row
          keyword: '', // 搜索关键字
        },
        calendarTypeOptions,

        del_id: '',
        del_index: null,
        dialogPvVisible: false, // 删除提示框
        dialogToggle: false, // 状态更改的提示框
      }
    },
    watch: {},
    created() {
      this.getList()
    },
    methods: {
      // 获取 table 列表
      getList() {
        this.listLoading = true
        listDownload(this.listQuery).then(res => {
          if (res.code == 0) {
            this.list = res.data.list
            this.total = res.data.total
            this.listLoading = false
          } else {
            this.listLoading = false
            this.$message({
              message: '请求失败',
              type: 'error'
            })
          }
        }).catch(res => {
          this.listLoading = false
        })

      },
      handleDownload(row) {
        sureDownload({
          centerIds: row.id
        }).then(res => {

          console.log('没处理的 :>> ', res);

          // 有待讨论，暂不能用
          var src = 'data:image/jpg;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String
            .fromCharCode(byte), ''))
          var link = document.createElement('a')
          link.href = src
          link.download = '下载内容.jpg'
          link.click()

          this.$message({
            message: '请求成功',
            type: 'success'
          })
        }).catch(res => {
          this.$message({
            message: '请求失败',
            type: 'error'
          })
        })
      },

      // 点击了删除
      handleDelete(row, index) {
        this.is_multip = false
        this.del_id = row.id
        this.del_index = index
        this.dialogPvVisible = true
      },
      // 点击了 批量删除
      handleDelmultip() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: '没有被选项!',
            type: 'error',
            duration: 4000,
            showClose: true,
            center: true
          })
        } else {
          this.is_multip = true
          this.dialogPvVisible = true
        }
      },
      // 确认了删除
      delData() {
        let ids = []

        if (this.is_multip) { // 批量删
          this.multipleSelection.forEach((item, i) => {
            ids.push(item.id)
          })
        } else {
          ids = [this.del_id]
        }
        let str_ids = ids.toString()

        console.log('删除传的数据 :>> ', str_ids);

        delDownload({
          centerIds: str_ids
        }).then(() => {
          this.dialogPvVisible = false
          // this.list.splice(this.del_index, 1)
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 4000
          })
        })
      },

      // 搜索
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      // 批量选择
      handleSelectionChange(val) {
        this.multipleSelection = val
      }
    }
  }
</script>

<style lang="scss">
  @import "~@/styles/variables.scss";

  .crud-input {
    border: 0;

    &.el-input--medium {
      font-size: 12px;
    }

    &.el-input--medium .el-input__inner {
      height: 27px !important;
      background: transparent;
      border: 0;
      -webkit-appearance: none;
      border-radius: 3px;
      // padding: 12px 5px 12px 15px;
      color: $text_dark;
      caret-color: $text_dark;

      &:-webkit-autofill {
        box-shadow: 0 0 0 1000px $my_opacity inset !important;
        -webkit-text-fill-color: $text_dark !important;
      }
    }

    .el-input-group__append {
      color: var(--app_primary);
      border: 0;
      border-left: 1px solid var(--app_primary);

      .el-button {
        // height: 27px;
        // border: 1px solid $my_primary !important;
        // background-color: #f11;
      }
    }
  }

  .el-dialog {
    .el-dialog__header {
      background-color: #f5f7f5 !important;
    }
  }

  .formitem-container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .el-form-item {
      width: 49%;
    }
  }
</style>


<style lang="scss" scoped>
  @import "~@/styles/variables.scss";

  .app-container {
    padding: 10px;
    background-color: #ffffff;

    .crud {
      // background-color: #f99;
      margin-bottom: 32px;
      display: flex;
      justify-content: space-between;

      .crud-input {
        height: 27px;
        width: 300px;
        border: 1px solid var(--app_primary);
        border-radius: 3px;
        // background-color: aqua;
      }
    }




    // background-color: #f99 !important;
    .el-table {
      .action {
        font-size: 13px;
        color: var(--app_primary);
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }
    }

    .el-dialog {
      .del-data {
        text-align: center;
        margin-bottom: 16px;

        img {
          width: 110px;
          height: 110px;
        }
      }

      .del-img {}
    }
  }
</style>
